package net.cyue.jpa;

import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.spi.PersistenceProvider;
import jakarta.persistence.spi.PersistenceProviderResolver;
import jakarta.persistence.spi.PersistenceProviderResolverHolder;
import jakarta.persistence.spi.PersistenceUnitInfo;

import java.util.HashMap;
import java.util.List;

public class CYuePersistence {

    public static EntityManagerFactory createEntityManagerFactory(
        PersistenceUnitInfo unitInfo
    ) {
        EntityManagerFactory emf = null;
        PersistenceProviderResolver resolver = PersistenceProviderResolverHolder.getPersistenceProviderResolver();
        List<PersistenceProvider> providers = resolver.getPersistenceProviders();
        for (PersistenceProvider p : providers) {
            emf = p.createContainerEntityManagerFactory(
                unitInfo,
                new HashMap<>()
            );
            if (emf != null) {
                break;
            }
        }
        if (emf == null) {
            throw new PersistenceException(
                "No Persistence provider for EntityManager named " +
                unitInfo.getPersistenceUnitName()
            );
        }
        return emf;
    }
}
